package com.tim.app.ui.activity.setting;

import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.StringUtil;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.callback.LoginCallBack;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.manager.WindowUtils;
import com.tim.app.server.api.API_Statistics;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.User;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.net.SignRequestParams;
import com.tim.app.server.result.LoginResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.ThirdAuthResult;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.activity.MainActivity;
import com.tim.app.util.SoftKeyboardUtil;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.UMLoginUtil;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * 登录
 * create at 2016/7/13
 */
public class PhoneLoginActivity extends BaseActivity {

    private static final String TAG = "PhoneLoginActivity";
    private EditText et_input_phone_num, et_input_password;
    private Button btLogin;
    private String phone, password;
    private UMLoginUtil loginUtil;

    private boolean canBack;

    @Override
    protected void onBeforeSetContentLayout() {
        super.onBeforeSetContentLayout();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login_phone;
    }

    @Override
    public void initView() {
        btLogin = (Button) findViewById(R.id.btLogin);
        et_input_phone_num = (EditText) findViewById(R.id.et_input_phone_num);
        et_input_password = (EditText) findViewById(R.id.et_input_password);
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.tvForgotPassword).setOnClickListener(this);
        findViewById(R.id.tvGotoRegist).setOnClickListener(this);
        findViewById(R.id.llLoginQQ).setOnClickListener(this);
        findViewById(R.id.llLoginWx).setOnClickListener(this);
        findViewById(R.id.llLoginSina).setOnClickListener(this);
        btLogin.setOnClickListener(this);

        et_input_phone_num.addTextChangedListener(new MyEditChangeListener());
        et_input_password.addTextChangedListener(new MyEditChangeListener());
        loginUtil = new UMLoginUtil(this);
    }

    @Override
    public void initData() {
        canBack = getIntent().getBooleanExtra("canBack", false);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (et_input_phone_num != null) {
            SoftKeyboardUtil.hideSoftKeyboard(et_input_phone_num);
        }
        if (et_input_password != null) {
            SoftKeyboardUtil.hideSoftKeyboard(et_input_password);
        }
    }

    @Override
    public void onBackPressed() {
        if (canBack) {
            MainActivity.start(this);
        } else {
            super.onBackPressed();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_back) {
            if (canBack) {
                MainActivity.start(this);
            }
            finish();
        } else if (v.getId() == R.id.btLogin) {
            phone = et_input_phone_num.getText().toString().trim();
            password = et_input_password.getText().toString().trim();
            if (checkLogin(phone, password)) {
                phoneLogin(phone, password);
            }
        } else if (v.getId() == R.id.llLoginQQ) {
            loginUtil.login(SHARE_MEDIA.QQ, new LoginCallBack() {
                @Override
                public void onFailed(String msg) {
                    ToastUtil.showToast(RT.getString(R.string.error_login_qq));
                }

                @Override
                public void onSuccess(String unionId, String name, String avatar, String token) {
                    appLogin(AppKey.LOGIN_TYPE_QQ, unionId, token);
                }
            });
        } else if (v.getId() == R.id.llLoginWx) {
            loginUtil.login(SHARE_MEDIA.WEIXIN, new LoginCallBack() {
                @Override
                public void onFailed(String msg) {
                    ToastUtil.showToast(RT.getString(R.string.error_login_wx));
                }

                @Override
                public void onSuccess(String unionid, String name, String avatar, String token) {
                    appLogin(AppKey.LOGIN_TYPE_WX, unionid, token);
                }
            });
        } else if (v.getId() == R.id.llLoginSina) {
            loginUtil.login(SHARE_MEDIA.SINA, new LoginCallBack() {
                @Override
                public void onFailed(String msg) {
                    ToastUtil.showToast(RT.getString(R.string.error_login_sina));
                }

                @Override
                public void onSuccess(String unionId, String name, String avatar, String token) {
                    appLogin(AppKey.LOGIN_TYPE_SINA, unionId, token);
                }
            });
        } else if (v.getId() == R.id.tvGotoRegist) {
            Intent intent = new Intent(PhoneLoginActivity.this, RegisterActivity.class);
            startActivityForResult(intent, AppKey.TYPE_MOBILE_REGIST);
        } else if (v.getId() == R.id.tvForgotPassword) {
            BindMobileOrResetPasswordActivity.startBindMobileOrResetPasswordActivity(PhoneLoginActivity.this, null, 0, AppKey.TYPE_FIND_WORD, "", "", AppKey.CODE_LOGIN_BIND_MOBILE);
        }
    }

    private void appLogin(final int platformType, final String platformUid, final String accessToken) {
        showLoadingDialog(R.string.loading_login);
        API_User.ins().loginByThird(TAG, platformType, platformUid, accessToken, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                hideLoadingDialog();
                String type = "";
                if (platformType == AppKey.LOGIN_TYPE_SINA) {
                    type = "wb";
                } else if (platformType == AppKey.LOGIN_TYPE_QQ) {
                    type = "qq";
                } else if (platformType == AppKey.LOGIN_TYPE_WX) {
                    type = "wx";
                }
                if (errCode == ResponseResult.ResultStatus.OK && !TextUtils.isEmpty(resultValue)) {
                    LoginResult result = new Gson().fromJson(resultValue, LoginResult.class);
                    if (null != result && null != result.getRes() && null != result.getRes().getHashmap()) {
                        if (result.getRes().getHashmap().getIsPerfectInfo() == 1) {
                            PerfectPersonInfomationActivity.start(PhoneLoginActivity.this, result.getRes().getHashmap().getUser(), AppKey.LOGIN_TYPE_MOBILE, -1);
                        } else {
                            if (null != result.getRes().getHashmap().getUser()) {
                                UserManager.ins().saveUserInfo(result.getRes().getHashmap().getUser());
                            }
                            if (!TextUtils.isEmpty(result.getRes().getHashmap().getAccessToken())) {
                                UserManager.ins().saveToken(result.getRes().getHashmap().getAccessToken());
                            }
                            UserManager.ins().saveLoginType(type);
                            API_Statistics.ins().addLoginData(TAG, PhoneLoginActivity.this, type, platformUid);
                            UserManager.ins().loginChat(result.getRes().getHashmap().getUser().getUserId());
                            EventManager.ins().sendEvent(EventTag.ACCOUNT_LOGIN, 0, 0, null);
                            JPushInterface.setAlias(PhoneLoginActivity.this, UserManager.ins().getChatId(UserManager.ins().getUserId()), new TagAliasCallback() {
                                @Override
                                public void gotResult(int i, String s, Set<String> set) {

                                }
                            });
                            Intent intent = new Intent(PhoneLoginActivity.this, MainActivity.class);
                            startActivity(intent);
                            PhoneLoginActivity.this.finish();
                            WindowUtils.getInStance().clearList();
                        }
                    }
                } else if (errCode == ResponseResult.ResultStatus.UN_REGIST) {
                    ThirdAuthResult result = new Gson().fromJson(resultValue, ThirdAuthResult.class);
                    if (null != result && null != result.getRes() && null != result.getRes().getPlatformuserobj()) {
                        User user = new User();
                        user.setImage(result.getRes().getPlatformuserobj().getProfileImageUrl());
                        user.setName(result.getRes().getPlatformuserobj().getScreenName());
                        user.setSex(result.getRes().getPlatformuserobj().getGender());
                        BindMobileOrResetPasswordActivity.startBindMobileOrResetPasswordActivity(PhoneLoginActivity.this, user, platformType, AppKey.TYPE_BING_MOBILE, platformUid, accessToken, AppKey.CODE_LOGIN_BIND_MOBILE);
                    }
                } else if (errCode == ResponseResult.ResultStatus.SUSPENED) {
                    ToastUtil.showToast(getString(R.string.suspenedPrompt));
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    /**
     * 检测登陆参数
     *
     * @param phone
     * @param password
     * @return
     */
    public boolean checkLogin(String phone, String password) {
        if (TextUtils.isEmpty(phone)) {
            ToastUtil.showToast(RT.getString(R.string.error_mobile_empty));
            return false;
        }
        if (!phone.matches(StringUtil.ZHENGZE_PHONE)) {
            ToastUtil.showToast(RT.getString(R.string.error_mobile_error));
            return false;
        }
        if (TextUtils.isEmpty(password) || !password.matches(StringUtil.ZHENGZE_PASSWORD)) {
            ToastUtil.showToast(RT.getString(R.string.error_password));
            return false;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (Activity.RESULT_OK == resultCode) {
            if (requestCode == AppKey.CODE_LOGIN_BIND_MOBILE) {
                EventManager.ins().sendEvent(EventTag.ACCOUNT_LOGIN, 0, 0, null);
                finish();
            } else if (requestCode == AppKey.TYPE_MOBILE_REGIST) {
                EventManager.ins().sendEvent(EventTag.ACCOUNT_LOGIN, 0, 0, null);
                finish();
            }
        }
    }

    private class MyEditChangeListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            updateBtn();
        }
    }

    private void updateBtn() {
        if (!TextUtils.isEmpty(et_input_phone_num.getText().toString().trim()) &&
                !TextUtils.isEmpty(et_input_password.getText().toString().trim())) {
            btLogin.setEnabled(true);
        } else {
            btLogin.setEnabled(false);
        }
    }

    /**
     * 手机登录
     *
     * @param phone
     * @param password
     */
    private void phoneLogin(final String phone, final String password) {
        showLoadingDialog();
        API_User.ins().loginByMobile(TAG, phone, SignRequestParams.MDString(password), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                hideLoadingDialog();
                if (errCode == ResponseResult.ResultStatus.OK && !TextUtils.isEmpty(resultValue)) {
                    LoginResult result = new Gson().fromJson(resultValue, LoginResult.class);
                    if (null != result && null != result.getRes() && null != result.getRes().getHashmap()) {
                        if (result.getRes().getHashmap().getIsPerfectInfo() == 1) {
                            PerfectPersonInfomationActivity.start(PhoneLoginActivity.this, result.getRes().getHashmap().getUser(), AppKey.LOGIN_TYPE_MOBILE, -1);
                        } else {
                            if (null != result.getRes().getHashmap().getUser()) {
                                UserManager.ins().saveUserInfo(result.getRes().getHashmap().getUser());
                            }
                            if (!TextUtils.isEmpty(result.getRes().getHashmap().getAccessToken())) {
                                UserManager.ins().saveToken(result.getRes().getHashmap().getAccessToken());
                            }
                            UserManager.ins().saveLoginType("phone");
                            API_Statistics.ins().addLoginData(TAG, PhoneLoginActivity.this, "phone", phone);
                            UserManager.ins().loginChat(result.getRes().getHashmap().getUser().getUserId());
                            EventManager.ins().sendEvent(EventTag.ACCOUNT_LOGIN, 0, 0, null);
                            JPushInterface.setAlias(PhoneLoginActivity.this, UserManager.ins().getChatId(UserManager.ins().getUserId()), new TagAliasCallback() {
                                @Override
                                public void gotResult(int i, String s, Set<String> set) {

                                }
                            });

                            Intent intent = new Intent(PhoneLoginActivity.this, MainActivity.class);
                            startActivity(intent);
                            PhoneLoginActivity.this.finish();
                            WindowUtils.getInStance().clearList();
                        }
                    }
                } else if (errCode == ResponseResult.ResultStatus.SUSPENED) {
                    ToastUtil.showToast(getString(R.string.suspenedPrompt));
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }
}
